package com.example.carborrow.dao;


import com.example.carborrow.model.Vip;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class VipDao {


    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public VipDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    private final  static String GET_ALL_VIPS_SQL ="SELECT * FROM Vip";
    //获取所有vip
    public List<Vip> getAllVip() {
        return jdbcTemplate.query(GET_ALL_VIPS_SQL,new VipRowMapper());
    }


    //按level获取
    private final static String GET_VIP_BY_LEVEL_SQL = "SELECT * FROM Vip WHERE vipLevel = ?";
    public Vip getVipByLevel(int level) {
        try {
            return jdbcTemplate.queryForObject(GET_VIP_BY_LEVEL_SQL, new VipRowMapper(), level);
        } catch (Exception e){
            return null;
        }
    }



    private final static String ADD_VIP_SQL = "INSERT INTO Vip (vipLevel,price,discountRate) VALUES (?, ?,?)";
    //添加vip
    public int addVip(Vip vip) {
        return jdbcTemplate.update(ADD_VIP_SQL, vip.getLevel(),vip.getVipPrice(),vip.getDiscountRate());
    }



    private final static String UPDATE_VIP_SQL ="UPDATE Vip SET price = ? , discountRate = ? WHERE vipLevel = ?";


    //按level更新
    public int updateVip(Vip vip) {
        return jdbcTemplate.update(UPDATE_VIP_SQL, vip.getVipPrice(),vip.getDiscountRate(),vip.getLevel());
    }




    private final static String DEL_VIP_SQL="DELETE FROM Vip WHERE vipLevel = ?";
    //删除vip
    public int deleteVip(int level) {
         return jdbcTemplate.update(DEL_VIP_SQL, level);
    }


    private static class VipRowMapper implements RowMapper<Vip> {
        @Override
        public Vip mapRow(ResultSet rs, int rowNum) throws SQLException {
            Vip vip = new Vip();
            vip.setLevel(rs.getInt("vipLevel"));
            vip.setVipPrice(rs.getBigDecimal("price"));
            vip.setDiscountRate(rs.getBigDecimal("discountRate"));

            return vip;
        }
    }




    
}
